package com.jeesite.modules.dataScreen.exceptions;

import cn.dev33.satoken.exception.NotLoginException;
import com.jeesite.modules.dataScreen.web.vo.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@Slf4j
@Component
@RestControllerAdvice
public class RestControllerAdviceHandler {

    @ExceptionHandler(Exception.class)
    public Result<String> exception(Exception e) {
        log.error("全局异常拦截,exception: {},{}", e.getMessage(), e);
        return Result.error(500, e.getMessage());
    }

    @ExceptionHandler(BgManageException.class)
    public Result<String> bgManageException(BgManageException e) {
        log.error("全局异常拦截,bgManageException: {}", e);
        return Result.error(e.getCode(), e.getMessage());
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Result<String> methodArgumentNotValidException(MethodArgumentNotValidException e) {
        String msg = e.getBindingResult().getFieldErrors()
                .stream()
                .map(n -> String.format("%s", n.getDefaultMessage()))
                .reduce((x, y) -> String.format("%s; %s", x, y))
                .orElse("参数输入有误");
        log.error("全局异常拦截,methodArgumentNotValidException: {}", e);
        return Result.error(500, msg);
    }

    @ExceptionHandler(NotLoginException.class)
    public Result<String> notLoginException(NotLoginException exception) {
        log.error("全局异常拦截,notLoginException: {}", exception);
        return Result.error(301, exception.getMessage());
    }
}
